package lib

import (
	"time"

	"database/sql"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

//数据库配置信息
type DInfo struct {
	Host     string
	Prot     string
	User     string
	Password string
	Database string
	Prefix   string `json:"prefix" form:"prefix"`
	Charset  string
}

var Mysql *gorm.DB
var err error

var DbInfo DInfo

func init() {
	//DbInfo.Prefix = "tx_"
	config := Config()
	/*
		fmt.Println("config", config1)
		config := make(map[string](map[string]interface{}))
		config["mysql"] = map[string]interface{}{
			"Host":     "127.0.0.1",
			"Prot":     "3306",
			"User":     "root",
			"Password": "root",
			"Database": "txgo",
			"Prefix":   "tx_",
			"Charset":  "utf8mb4",
		}
	*/
	//var s DInfo
	//	fmt.Println(DbInfo)
	DbInfo.Host = (config["mysql"]["Host"]).(string)
	DbInfo.Prot = (config["mysql"]["Prot"]).(string)
	DbInfo.User = (config["mysql"]["User"]).(string)
	DbInfo.Password = (config["mysql"]["Password"]).(string)
	DbInfo.Database = (config["mysql"]["Database"]).(string)
	DbInfo.Prefix = (config["mysql"]["Prefix"]).(string)
	DbInfo.Charset = (config["mysql"]["Charset"]).(string)

	//	fmt.Printf("sss %s=>%T \r\n", ss, ss)
	//DbInfo = s

	//	fmt.Println("sss", DbInfo)

	dsn := DbInfo.User + ":" + DbInfo.Password + "@tcp(" + DbInfo.Host + ":" + DbInfo.Prot + ")/" + DbInfo.Database + "?charset=" + DbInfo.Charset + "&parseTime=True&loc=Local"
	//dsn := "root:root@tcp(127.0.0.1:3306)/txgo?charset=utf8mb4&parseTime=True&loc=Local"
	//db, _ := gorm.Open(dsn)
	//	id := c.Query("id")
	//fmt.Println(dsn)
	Mysql, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})

	if err == nil {

	}
	var MysqlDB *sql.DB
	MysqlDB, err = Mysql.DB()

	// SetMaxIdleConns 设置空闲连接池中的最大连接数。
	MysqlDB.SetMaxIdleConns(20)

	// SetMaxOpenConns 设置到数据库的最大打开连接数。
	MysqlDB.SetMaxOpenConns(200)

	// SetConnMaxLifetime 设置连接可以重用的最长时间。
	MysqlDB.SetConnMaxLifetime(time.Hour)

	//	defer MysqlDB.Close()
}

type FieldTable struct {
	Field string `json:"field" form:"field"`
	Type  string `json:"type" form:"type"`
}

func Desc(table string) (_fieldlist []FieldTable) {
	//var _fieldlist []FieldTable
	//var _list
	/*
		var data map[int](map[string]interface{})
		fmt.Printf("%s=>%T", "desc "+DbInfo.Prefix+table, "desc "+DbInfo.Prefix+table)
		Mysql.Exec("desc `tx_activity`").Scan(&data) //Debug().

		fmt.Println("desc tx_activity", data)
	*/

	//	Mysql.Debug().Table(DbInfo.Prefix+"activity").Where("id = ?", 1).Scan(&data) //Debug().
	Mysql.Raw(" desc " + DbInfo.Prefix + table).Scan(&_fieldlist) //Debug().
	//fmt.Println("\r\n mysql desc tx_activity", data)
	return _fieldlist
}
